using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

/// <summary>
/// 计时器
/// 用于统一update计时
/// 所有需要在update进行计时的方法都可以注册在此方法中实现方法回调
/// </summary>
public class Timer : Singleton<Timer>
{
    public static Dictionary<int, Action> eventDict = new();//hashcode作为key

    public float coolDown = 1f;

    // Update is called once per frame
    void Update()
    {
        if (coolDown > 0f)
        {
            coolDown -= Time.deltaTime;
        }
        else
        {
            coolDown += 1f;
            UpdateEvent();
        }
    }

    public static void AddEvent(int code, Action action)
    {
        if(eventDict.ContainsKey(code))
        {
            Debug.LogError("已添加过该事件，请勿重复添加");
        }
        else
        {
            eventDict.Add(code, action);
        }
        
    }

    public void UpdateEvent()
    {
        foreach (var item in eventDict.Values)
        {
            item.Invoke();
        }
    }

    public static void RemoveEvent(int code)
    {
        if (eventDict.ContainsKey(code))
        {
            eventDict.Remove(code);
        }
        else
        {
            Debug.LogError($"{code}未注册计时事件");
        }
    }


    protected override void OnDestroy()
    {
        base.OnDestroy();
        eventDict.Clear();
    }
}
